import { defineStore } from 'pinia';
import type { PersistenceOptions } from 'pinia-plugin-persistedstate';
import { hasUser, registerUser } from '@/apis/user';

interface UserState {
  loginTime?: number;
  userInfo?: IUserInfo;
}

export const useUserStore = defineStore('user', {
  state: (): UserState => ({
    loginTime: void 0,
    userInfo: void 0,
  }),
  actions: {
    async userLogin(username: string, password: string) {
      const result = await hasUser(username, password);
      console.log(result, 'result');

      if (result) {
        this.loginTime = Date.now();
        const { name, phone, avatar } = result;
        this.userInfo = { name, phone, avatar };
      }
    },
    async registerUser(data: IRegistryUser) {
      const result = await registerUser(data);
      if (result) {
        this.loginTime = Date.now();
      }
    },
  },
  persist: {
    key: 'vue3-admin-user',
    storage: localStorage, // 存储方式
    paths: ['loginTime', 'userInfo'], // 指定需要持久化的字段
  } as PersistenceOptions<UserState>,
});
